//
//  YZSwineryHealthVC.m
//  VET
//
//  Created by 刘文靖 on 2018/7/18.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZSwineryHealthVC.h"
#import "YZActionSheet.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
#import "YZCreateNoteVC.h"
#import "PopoverView.h"
#import "YZSwineryModel.h"
#import "MJExtension.h"
#import "YZSwineryListCell.h"
#import "YZAutoItemModel.h"
#import "YZWorkbenchAPI.h"
#import "YZRouter+AutoVC.h"
#import "MJRefresh.h"
#import "YZPigGroupDocVC.h"
#import "YZAutoFormHeader.h"
#import "YZSanitarianVC.h"
#import "YZWorkNoteModel.h"
#import "YZSwinerySearchResultController.h"
#import "YZSwineHeaderView.h"
@interface YZSwineryHealthVC ()<UITableViewDelegate,UITableViewDataSource,YZActionSheetDelegate,YZSwineryListCellDelegate,UIGestureRecognizerDelegate,YZSwineHeaderViewDelegate>
@property (strong, nonatomic) NSMutableArray<YZSwineryModel *> *dataSource;
@property (strong, nonatomic) UIView *emptyView;
@property (strong, nonatomic) YZSwineHeaderView *navigationView;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YZSwineryModel *selectedModel;
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
@property (assign, nonatomic) NSInteger currentPage;
@end
#define kPagePerCount 10
#define knaviBarHeight kStatusBarHeight + 48
@implementation YZSwineryHealthVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColorWithHex(0xf5f5f5);
    [self setupNavigationBar];
    [self setupRefresh];
    
    // 编辑新增猪群后更新
    @weakify(self)
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:kSwineryRefreshNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        
        // 获取新数据
        @strongify(self)
        [self.tableView.mj_header beginRefreshing];
        
    }];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    // 支持右滑返回
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupNavigationBar{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    YZSwineHeaderView *headerView = [[YZSwineHeaderView alloc] initWithType:YZSwineHeaderViewHerd];
    headerView.delegate = self;
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(144 + kStatusBarHeight);
    }];
    self.navigationView = headerView;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.tableFooterView = [UIView new];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadNewData];
    }];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 隐藏状态
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}


- (void)loadNewData{
    @weakify(self)
    [[YZSwineryModelAPI requestSwineryList:0 batchNo:nil] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        self.currentPage = 1;
        self.dataSource = [YZSwineryModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
        if (self.dataSource.count < kPagePerCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView.mj_header endRefreshing];
        [self refreshTableView];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData{
    @weakify(self)
    [[YZSwineryModelAPI requestSwineryList:self.currentPage batchNo:nil] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        ++self.currentPage;
        [self.tableView.mj_footer endRefreshing];
        [self.dataSource addObjectsFromArray:[YZSwineryModel mj_objectArrayWithKeyValuesArray:dict[@"list"]]];
        if (self.dataSource.count % kPagePerCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer resetNoMoreData];
        }
        
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_footer endRefreshing];
    }];
}


- (void)refreshTableView{
    if (self.dataSource.count) {
        self.emptyView.hidden = YES;
    }else{
        [self showEmptyView];
    }
    [self.tableView reloadData];
}
- (UITableView *)tableView{
    if (!_tableView) {
         _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, knaviBarHeight, kScreenWidth,kScreenHeight - knaviBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = 163;
        [_tableView registerClass:[YZSwineryListCell class] forCellReuseIdentifier:@"YZSwineryListCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UIView * clearview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 96)];
        clearview.backgroundColor = [UIColor clearColor];
        _tableView.tableHeaderView = clearview;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (void)showEmptyView{
    self.tableView.mj_footer.hidden = YES;
    if (self.emptyView) {
        self.emptyView.hidden = NO;
    }else{
        self.emptyView = [[UIView alloc] init];
        self.emptyView.layer.contents = (__bridge id)[UIImage imageNamed:@"card_background"].CGImage;
        
        UILabel *emptyLabel = [[UILabel alloc] init];
        emptyLabel.text = @"还没有猪群的健康卡";
        emptyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        emptyLabel.textColor = kColorWithHex(0x9b9b9b);
        [self.emptyView addSubview:emptyLabel];
        [emptyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.height.mas_equalTo(20);
            make.top.offset(59);
        }];
        
        UIButton *addBtn = [[UIButton alloc] init];
        [addBtn setTitle:@"创建一张卡" forState:UIControlStateNormal];
        [addBtn setTitleColor:kColorWithHex(0x32BE60) forState:UIControlStateNormal];
        addBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [addBtn setImage:[UIImage imageNamed:@"empty_add"] forState:UIControlStateNormal];
        addBtn.layer.borderWidth = 1;
        addBtn.layer.borderColor = kColorWithHex(0x32BE60).CGColor;
        addBtn.layer.cornerRadius = 4;
        [self.emptyView addSubview:addBtn];
        [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(120, 40));
            make.centerX.offset(0);
            make.top.mas_equalTo(emptyLabel.mas_bottom).offset(21);
        }];
        [self.tableView addSubview:self.emptyView];
        [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(11);
            make.right.offset(-11);
            make.top.offset(108);
            make.size.mas_equalTo(CGSizeMake(kScreenWidth - 22, 182));
        }];
        [[addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwinery"];
        }];
    }
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZSwineryListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YZSwineryListCell"];
    cell.model = self.dataSource[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YZPigGroupDocVC * pigGroupVC = [YZPigGroupDocVC new];
    pigGroupVC.model = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:pigGroupVC animated:YES];
}

#pragma mark - YZSwineArchieveCellDelegate
- (void)cellDidClickManage:(YZSwineryListCell *)cell{
    
    NSArray *array = nil;
    if (cell.model.isFinished) {
        array = @[@"添加笔记",@"删除"];
    } else {
        array = @[@"编辑修改",@"死淘登记",@"转入转出",@"结束批次",@"添加笔记",@"删除"];
    }
    YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:nil sheetTitles:array cancleBtnTitle:@"取消" sheetStyle:YZActionSheetDefault delegate:self];
    sheet.sheetHeight = 55;
    sheet.subtitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.subtitleColor = kColorWithHex(0x393939);
    sheet.lineColor = kColorWithHex(0xD9D9D9);
    sheet.cancleHeight = 55;
    sheet.bottomMarginHeight = 15;
    sheet.cancelTitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.cancelTitleColor = kColorWithHex(0x393939);
    self.selectedModel = cell.model;
    self.selectedIndexPath = [self.tableView indexPathForCell:cell];
    [sheet show];
}

#pragma mark - YZActionSheetDelegate
/**
 点击actionSheet代理方法
 
 @param actionSheet actionSheet
 @param buttonIndex index
 */
- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex{
    
    if (self.selectedModel.isFinished) {
        // 结批流程
        switch (buttonIndex) {
            case 0://添加笔记
            {
                YZCreateNoteVC *noteVC = [[YZCreateNoteVC alloc] init];
                NSMutableArray *archiveList = [NSMutableArray array];
                [archiveList addObject:[YZArchiveModel convertWithSwinery:self.selectedModel]];
                noteVC.archiveList = archiveList;
                [[YZRouter sharedInstance] pushVC:noteVC];
            }
                break;
                
            case 1:{//删除
               [self deleteSwinery];
            }break;
            default:
                break;
        }
                
    } else {
        switch (buttonIndex) {
            case 0://编辑修改
            {
                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwinery" params:@{@"params" : @{kURI : kURI, @"id" : swineryId}}];
            }
                
                break;
                
            case 1://死淘登记
            {
                // 死淘登记
//                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                NSMutableDictionary *params = [self.selectedModel mj_keyValues];
                [[YZRouter sharedInstance] yz_atuoPush:@"cardDeadSignSwinery" params:@{@"params" : params}];
            }
                
                break;
                
            case 2://转入转出
            {
                // 转入转出
                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                [[YZRouter sharedInstance] yz_atuoPush:@"cardTransferSwinery" params:@{@"params" : @{@"id" : swineryId, @"batchNo" : self.selectedModel.batchNo, @"realQty" : @(self.selectedModel.realQty)}}];
            }
                
                break;
                
            case 3://结束批次
            {
                if (self.selectedModel.realQty > 0) {
                    
                    YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
                    @weakify(self)
                    [customView setupMessage:[NSString stringWithFormat:@"猪群%@实时存栏不为0， 不可进行结批操作！", self.selectedModel.batchNo] confirmTitle:@"知道了！" confirmHandler:^{
                        
                        @strongify(self)
                        [self.YZ_popupController dismiss];
                        
                    }];
                    [self.YZ_popupController presentContentView:customView];
                } else {
                    
                    // 结批
                    NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                    [[YZRouter sharedInstance] yz_atuoPush:@"cardFinishSwinery" params:@{@"params" : @{@"id" : swineryId, @"batchNo" : self.selectedModel.batchNo}}];
                }
            }
                
                break;
                
            case 4://添加笔记
            {
                YZCreateNoteVC *noteVC = [[YZCreateNoteVC alloc] init];
                NSMutableArray *archiveList = [NSMutableArray array];
                [archiveList addObject:[YZArchiveModel convertWithSwinery:self.selectedModel]];
                noteVC.archiveList = archiveList;
                [self.navigationController pushViewController:noteVC animated:YES];
            }
                break;
                
            case 5:{//删除
                [self deleteSwinery];
            }
                break;
                
            default:
                break;
        }
    }
}
- (void)actionSheetCancle:(YZActionSheet *)actionSheet{
    
}

#pragma mark - YZSwineHeaderViewDelegate
- (void)backButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)menuButtonClick:(UIButton *)sender{
    PopoverView *popoverView = [PopoverView popoverView];
    popoverView.showShade = YES; // 显示阴影背景
    [popoverView showToView:sender withActions:[self POPActions]];
}

- (void)searchButtonClicked{
    YZSwinerySearchResultController *searchVC = [[YZSwinerySearchResultController alloc] init];
    [self presentViewController:searchVC animated:NO completion:nil];
}
#pragma mark - PopoverVie
- (NSArray<PopoverAction *> *)POPActions {
    // 新增猪群 action
    PopoverAction *pigtAction = [PopoverAction actionWithTitle:@"新增猪群" handler:^(PopoverAction *action) {
        
        [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwinery"];
        
    }];
    // 新增免疫 action
    PopoverAction *immuneAction = [PopoverAction actionWithTitle:@"新增免疫" handler:^(PopoverAction *action) {
        
        [[YZRouter sharedInstance] yz_atuoPush:@"immuneSwinery"];
        
    }];
    // 新增保健 action
    PopoverAction *healthAction = [PopoverAction actionWithTitle:@"新增保健" handler:^(PopoverAction *action) {
        
        YZSanitarianVC *sanitarianVC = [[YZSanitarianVC alloc] init];
        sanitarianVC.objectType = @"herd";
        [self.navigationController pushViewController:sanitarianVC animated:YES];
        
    }];
    
    return @[pigtAction, immuneAction, healthAction];
}

- (void)deleteSwinery{
    YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
    @weakify(self)
    [customView setupUIWithTitle:nil message:[NSString stringWithFormat:@"确定要删除%@猪群？删除后不可恢复当前猪群已记录信息。",self.selectedModel.batchNo] confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
        
        @strongify(self)
        // 删除猪群
        NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
        [[YZWorkbenchAPI deleteSwineryAPI:swineryId] subscribeError:^(NSError * _Nullable error) {
            @strongify(self)
            [self.YZ_popupController dismiss];
            
        } completed:^{
            @strongify(self)
            [self.YZ_popupController dismiss];
            [self.dataSource removeObject:self.selectedModel];
            [self.tableView deleteRowsAtIndexPaths:@[self.selectedIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
            if (self.dataSource.count == 0) {
                [self showEmptyView];
            }
        }];
        
    } cancelHandler:^{
        @strongify(self)
        [self.YZ_popupController dismiss];
    }];
    [self.YZ_popupController presentContentView:customView];
}

#pragma scrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.dataSource.count == 0) return;
    CGFloat topImageView2y = 96;
    float contentOffsety = scrollView.contentOffset.y;
    self.navigationView.searchBtn.alpha = (topImageView2y - contentOffsety * 2)/topImageView2y;
    if (contentOffsety > 0) {
        [self.navigationView.searchBtn setTop:(knaviBarHeight + 20 - contentOffsety)];
    }
    if (self.navigationView.searchBtn.alpha == 1) {
        [self.view bringSubviewToFront:self.navigationView];
    }else{
        [self.view bringSubviewToFront:self.tableView];
    }
    self.navigationView.rightSearchBtn.alpha = 1-self.navigationView.searchBtn.alpha;
}

@end
